package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.order.OrderConfig;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.pojo.order.OrderIterms;
import com.qingcheng.pojo.order.OrderLog;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderConfigService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

<<<<<<< HEAD
import java.util.*;
=======
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
>>>>>>> origin/zzh
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    
    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }
    
    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }
    
    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }
    
    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }



    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }
    
    @Autowired
    private CartService cartService;
    
    @Reference
    private SkuService skuService;
    
    @Autowired
    private IdWorker idWorker;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
<<<<<<< HEAD

    @Autowired
<<<<<<< HEAD
    private PreferentialService preferentialService;


=======
    
>>>>>>> origin/zd
=======
    private OrderConfigService orderConfigService;

>>>>>>> origin/zzh
    /**
     * 新增
     * @param order
     */
    @Transactional
    public Map<String,Object> add(Order order) {
    
        //1.获取选中的购物车
        List<Map<String, Object>> cartList = cartService.findNewOrderItemList(order.getUsername());
        List<OrderItem> orderItemList = cartList.stream().filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
    
        //2.扣减库存
        if(!skuService.deductionStock(orderItemList)){
            throw  new RuntimeException("库存不足！");
        }
        try {
            //3.保存订单主表
            order.setId( idWorker.nextId()+"" );
    
            IntStream numStream = orderItemList.stream().mapToInt(OrderItem::getNum);
            IntStream moneytStream = orderItemList.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();
            int totalMoney = moneytStream.sum();
            int preMoney = cartService.preferential(order.getUsername());  //满减优惠金额
    
            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney); //总金额
            order.setPreMoney(preMoney);//优惠金额
            order.setPayMoney( totalMoney-preMoney );//支付金额
            order.setCreateTime(new Date());//订单创建时间
            order.setOrderStatus("0");//订单状态
            order.setPayStatus("0");//支付状态
            order.setConsignStatus("0");//发货状态
    
            orderMapper.insert(order);


            //4.保存订单明细表
            //打折比例
<<<<<<< HEAD
//            double proportion= (double)order.getPayMoney()/totalMoney;
//
//            for(OrderItem orderItem:orderItemList ){
//                orderItem.setId(idWorker.nextId()+"" );
//                orderItem.setOrderId( order.getId() );
//                orderItem.setPayMoney((int)(orderItem.getMoney()*proportion)  );

            /**分类Id     money
             *  1           100
             *  2           200
             *  3           300
             *
             */

            Map<Integer, IntSummaryStatistics> collect = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getCategoryId3, Collectors.summarizingInt(OrderItem::getMoney)));//各分类的钱
            Map<Integer, IntSummaryStatistics> collect2 = orderItemList.stream().collect(Collectors.groupingBy(OrderItem::getCategoryId3, Collectors.summarizingInt(OrderItem::getNum)));//各分类的数量

            for (OrderItem orderItem : orderItemList) {
                //在添加商品到购物车时，已经添加了一部分能填写的数据，一些不能填写的数据还在空着
                //现在要保存到数据库，就需要把剩余的数据补全，而且也能获取到这些数据
                //商品项也需要分表，所以id要自己生成
                orderItem.setId(idWorker.nextId()+"");
                //一个订单id对应很多个商品项。。从商品项，可以找到属于哪一个订单。从订单可以找到多个商品项
                orderItem.setOrderId(order.getId());


                int money = orderItem.getPrice() * orderItem.getNum();//优惠前的总金额

                Set<Integer> ids = collect.keySet();//分类
                Integer premoney =0;
                for (Integer id : ids) {//id为分类名
                    if(id==orderItem.getCategoryId3()){//与订单相同的分类名
                        Integer sum1 = Math.toIntExact(collect.get(id).getSum());//collect.get(id).getSum()某个分类的总钱数
                        //同一分类的总个数
                        Integer totalnum = Math.toIntExact(collect2.get(id).getSum());
                        Integer preferential1 = preferentialService.findPreMoneyByCategoryId(orderItem.getCategoryId3(), sum1);//某一分类的总优惠

                        premoney =(preferential1 / totalnum)*orderItem.getNum();//某一个订单的总的优惠钱优惠
                        break;
                    }
                }
                orderItem.setPayMoney(money-premoney);//每一个优惠后的钱数
                //保存到数据库里
=======
            double proportion= (double)order.getPayMoney()/totalMoney;
    
            for(OrderItem orderItem:orderItemList ){
                orderItem.setId(idWorker.nextId()+"" );
                orderItem.setOrderId( order.getId() );
                orderItem.setPayMoney((int)(orderItem.getMoney()*proportion)  );
    
>>>>>>> origin/zd
                orderItemMapper.insert(orderItem);
                //int x=1/0;
            }
<<<<<<< HEAD
=======
    
            //int x=1/0;
>>>>>>> origin/zd
        } catch (Exception e) {
            e.printStackTrace();
            //发送回滚消息
            rabbitTemplate.convertAndSend("","queue.skuback", JSON.toJSONString(orderItemList));
            throw new RuntimeException("创建订单失败");
        }
<<<<<<< HEAD
    
=======

        //超时未支付订单
        rabbitTemplate.convertAndSend("","queue.ordercreate",order.getId());
>>>>>>> origin/jtt
        //5.清除购物车
        cartService.deleteCheckedCart( order.getUsername()  );
    
        Map map=new HashMap();
        map.put("ordersn",order.getId());
        map.put("money",order.getPayMoney());
        return map;
    
    }
    
    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }
    
    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 拆分订单2222
     * @param orderItemList
     */
    @Transactional
    public void split(List<OrderItem> orderItemList) {

        if(orderItemList.size()==0||"".equals(orderItemList)){
            return;
        }

        for (OrderItem _orderItem : orderItemList) {
            //该_orderItem中只有id和num两个字段，现根据id查询完整的orderItem
            OrderItem orderItem = orderItemMapper.selectByPrimaryKey(_orderItem.getId());
            if(orderItem.getNum()<_orderItem.getNum()){
                throw new RuntimeException("拆分数量大于现有数量");
            }
        }
        //根据明细的OrderId查询订单
        Order order = orderMapper.selectByPrimaryKey(orderItemMapper.selectByPrimaryKey(orderItemList.get(0).getId()).getOrderId());
        //创建新订单
        Order newOrder=new Order();
        BeanUtils.copyProperties(order,newOrder);
        newOrder.setId(String.valueOf(idWorker.nextId()));

        //订单数量，订单金额，订单更新时间，优惠金额，实付金额
        int newOrderNum=0;
        int newOrderMoney=0;
        int neworderPreMoney=0;//
        int newOrderPayMoney=0;

        for (int i = 0; i < orderItemList.size(); i++) {

        }
        for (int i = 0; i < orderItemList.size(); i++) {
            //该_orderItem中只有id和num两个字段，现根据id查询完整的orderItem
            OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemList.get(i).getId());
            OrderItem newOrderItem=new OrderItem();
            BeanUtils.copyProperties(orderItem,newOrderItem);

            //更新原有明细的数量
            newOrderNum+=orderItemList.get(i).getNum();
            newOrderMoney+=orderItem.getPrice()*newOrderNum;

            orderItem.setNum(orderItem.getNum()-orderItemList.get(i).getNum());
            orderItemMapper.updateByPrimaryKeySelective(orderItem);

            //更新新明细的orderId和数量

            newOrderItem.setId(idWorker.nextId()+"");

            System.out.println("原明细："+orderItem.getId());
            System.out.println("新明细："+newOrderItem.getId());
            newOrderItem.setNum(orderItemList.get(i).getNum());
            newOrderItem.setOrderId(newOrder.getId());
            orderItemMapper.insert(newOrderItem);
        }

        //原订单改变的值（订单数量，订单金额，订单更新时间，优惠金额，实付金额）
        //优惠金额
        int zongyouhui=order.getPreMoney();
        int zongfukuan=order.getPayMoney();
        order.setPreMoney((order.getTotalMoney()-newOrderMoney)/order.getTotalMoney()*order.getPreMoney());
        //总数量
        order.setTotalNum(order.getTotalNum()-newOrderNum);
        //总金额
        order.setTotalMoney(order.getTotalMoney()-newOrderMoney);
        //实付金额
        order.setPayMoney(order.getTotalMoney()-order.getPreMoney());
        order.setUpdateTime(new Date());
        //更新原订单
        orderMapper.updateByPrimaryKeySelective(order);

        //更新新订单
        newOrder.setUpdateTime(new Date());
        newOrder.setTotalNum(newOrderNum);
        newOrder.setTotalMoney(newOrderMoney);
        newOrder.setPreMoney(zongyouhui-order.getPreMoney());
        newOrder.setPayMoney(zongfukuan-order.getPayMoney());
        orderMapper.insert(newOrder);
        //记录订单日志
        OrderLog orderLog1=new OrderLog();
        orderLog1.setId(String.valueOf(idWorker.nextId()));
        orderLog1.setOperater("admin");
        orderLog1.setOperateTime(new Date());
        orderLog1.setOrderId(order.getId());
        orderLog1.setOrderStatus(order.getOrderStatus());
        orderLog1.setPayStatus(order.getPayStatus());
        orderLog1.setConsignStatus(order.getConsignStatus());
        orderLog1.setRemarks("将订单"+order.getId()+"拆分,新订单Id为"+newOrder.getId());
        orderLogMapper.insert(orderLog1);

    }


    @Autowired
    private OrderLogMapper orderLogMapper;
    
    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        System.out.println("调用修改订单状态");
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order!=null && "0".equals( order.getPayStatus() )){
            //修改订单状态等信息
            order.setPayStatus("1");//支付状态
            order.setOrderStatus("1");//订单状态
            order.setUpdateTime(new Date());//修改日期
            order.setPayTime(new Date());//支付日期
            order.setTransactionId(transactionId);//交易流水号
            orderMapper.updateByPrimaryKeySelective(order);//修改
    
            //记录订单日志
            OrderLog orderLog=new OrderLog();
            orderLog.setId( idWorker.nextId()+"" );
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//操作时间
            orderLog.setOrderStatus("1");//订单状态
            orderLog.setPayStatus("1");//支付状态
            orderLog.setRemarks("支付流水号："+transactionId);//备注
            orderLog.setOrderId(orderId);
            orderLogMapper.insert(orderLog);
    
        }


    }
    
    /**
     * 根据orderId查询组合实体类  OrderIterms
     * @param id 订单id
     * @return 
     */ 
    @Override
    public OrderIterms findOrderItemsById(String id) {
        OrderIterms orderIterms = new OrderIterms();
        Order order = orderMapper.selectByPrimaryKey(id);
    
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",order.getId());
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        orderIterms.setOrder(order); 
        orderIterms.setOrderItemList(orderItems);
        return orderIterms;
    }
    
    /**
     * 合并订单 返回合并结果 0代表成功 1代表失败 String代表错误信息
     * */
    @Transactional
    public Map<Integer, String> mergeOrder(String orderId1, String orderId2) {
        //定义一个map来封装结果
        Map<Integer, String> map = new HashMap<Integer, String>();

        //通过id查询对象,如果不存在则出异常
        Order order1=null;
        Order order2=null;
        try {
            order1 = orderMapper.selectByPrimaryKey(orderId1);
            order2 = orderMapper.selectByPrimaryKey(orderId2);
        } catch (Exception e) {
            e.printStackTrace();
            map.put(1,"合并失败,主订单或者次订单不存在");
            return map;
        }
        if(!"1".equals(order1.getOrderStatus()) || !"1".equals(order2.getOrderStatus())){
            map.put(1,"合并失败,订单状态有误");
            return map;
        }
        if(!"1".equals(order1.getPayStatus()) || !"1".equals(order2.getPayStatus())){
            map.put(1,"合并失败,支付状态有误");
            return map;
        }
        if(!"0".equals(order1.getConsignStatus()) || !"0".equals(order2.getConsignStatus())){
            map.put(1,"合并失败,发货状态有误");
            return map;
        }
        if(!"0".equals(order1.getIsDelete()) || !"0".equals(order2.getIsDelete())){
            map.put(1,"已删除订单无法进行合并");
            return map;
        }
        if(!order1.getUsername().equals(order2.getUsername())){
            map.put(1,"合并失败,下单用户不一致");
            return map;
        }
        if(!order1.getPayType().equals(order2.getPayType())){
            map.put(1,"合并失败,支付类型不一致");
            return map;
        }
        if (!order1.getReceiverAddress().equals(order2.getReceiverAddress()) || !order1.getReceiverContact().equals(order2.getReceiverContact()) || !order1.getReceiverMobile().equals(order2.getReceiverMobile())){
            map.put(1,"合并失败,收件人信息不一致");
            return map;
        }

        //获取主订单明细列表
        Example example1 = new Example(OrderItem.class);
        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("orderId",order1.getId());
        List<OrderItem> orderItemList1 = orderItemMapper.selectByExample(example1);

        //获取次订单明细列表
        Example example2 = new Example(OrderItem.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("orderId",order2.getId());
        List<OrderItem> orderItemList2 = orderItemMapper.selectByExample(example2);

        boolean flag=true;  //true代表该次订单订单明细sku不与主订单的明细重复
        for (OrderItem orderItem : orderItemList2) {
            flag=true;  //每次循环重置
            //遍历主订单的订单明细列表 筛选明细中存在相同sku的明细 进行数量,总金额,实付金额,重量,运费更新
            for (OrderItem item : orderItemList1) {
                if (item.getSkuId().equals(orderItem.getSkuId())){
                    item.setNum(item.getNum()+orderItem.getNum());
                    item.setMoney(item.getMoney()+orderItem.getMoney());
                    item.setPayMoney(item.getPayMoney()+orderItem.getPayMoney());
                    item.setWeight(item.getWeight()+orderItem.getWeight());
                    item.setPostFee(item.getPostFee()+orderItem.getPostFee());
                    orderItemMapper.updateByPrimaryKey(item);
                    flag=false;
                }
            }

            if (flag){
                //将次订单的订单明细中的订单ID更改为主订单的ID
                orderItem.setOrderId(order1.getId());
                //更新订单明细到数据库
                orderItemMapper.updateByPrimaryKey(orderItem);
            }
        }

       /* Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",order2.getId());
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItemList) {
            //将次订单的订单明细中的订单ID更改为主订单的ID
            orderItem.setOrderId(order1.getId());
            //更新订单明细到数据库
            orderItemMapper.updateByPrimaryKey(orderItem);
        }*/

        order1.setTotalNum(order1.getTotalNum()+order2.getTotalNum());
        order1.setTotalMoney(order1.getTotalMoney()+order2.getTotalMoney());
        order1.setPreMoney(order1.getPreMoney()+order2.getPreMoney());
        order1.setPostFee(order1.getPostFee()+order2.getPostFee());
        order1.setPayMoney(order1.getPayMoney()+order2.getPayMoney());
        order1.setUpdateTime(new Date());

        orderMapper.updateByPrimaryKey(order1);

        order2.setUpdateTime(new Date());
        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKey(order2);

        map.put(0,"合并成功");
        return map;
    }

    @Override
    public void overTime() {
        OrderConfig orderConfig = orderConfigService.findById(1);//因为超时设置只有一种
        Integer orderTimeout = orderConfig.getOrderTimeout();
        LocalDateTime time = LocalDateTime.now().minusMinutes(orderTimeout);//获取本地时间向前的超时时间

        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime",time);//超时的订单
        criteria.andEqualTo("payStatus","0");//支付状态是0,也是就未付款的订单
        criteria.andEqualTo("isDelete","0");//未删除
        criteria.andNotEqualTo("orderStatus","4");//不是已关闭的订单
        List<Order> orderList = orderMapper.selectByExample(example);
        for (Order order : orderList) {
            order.setCloseTime(new Date());//修改关闭时间为当前
            order.setUpdateTime(new Date());//修改时间设置为当前
            order.setOrderStatus("4");//将订单状态设置为关闭
            orderMapper.updateByPrimaryKey(order);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setRemarks("订单超时自动关闭");
            orderLog.setOperateTime(new Date());
            orderLog.setOperater("system");//操作员为系统自动关闭
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());//付款状态设置为订单的付款状态
            orderLog.setOrderId(order.getId());
            orderLog.setConsignStatus("0");
            orderLogMapper.insert(orderLog);
        }
    }


   @Autowired
   private WxPayServiceImpl wxPayService;
    /**
     * 关闭订单
     */
    public void shutDownOrder(String orderId) {
        //调用微信关闭订单的方法
        Map map = wxPayService.shutDownOrder(orderId);
        if(!"SUCCESS".equals(map.get("return_code"))){
            throw new RuntimeException("微信关闭订单失败");
        }
        Order order = orderMapper.selectByPrimaryKey(orderId);

        //修改订单表的订单状态
        if(order!=null&&"0".equals(order.getPayStatus())){
            order.setCloseTime(new Date());//交易关闭时间
            order.setOrderStatus("0");//订单状态
            order.setPayStatus("0");//支付状态
            order.setUpdateTime(new Date());//修改日期
            orderMapper.updateByPrimaryKeySelective(order);

            //记录订单日志
            OrderLog orderLog=new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("system");//系统
            orderLog.setOperateTime(new Date());//操作时间
            orderLog.setOrderStatus("0");//订单状态
            orderLog.setPayStatus("0");//支付状态
            orderLog.setOrderId(orderId);
            orderLog.setRemarks("订单超时关闭");
            orderLogMapper.insert(orderLog);
            //恢复商品表库存
            Example example=new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId",order.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItemList) {
                Sku sku = skuService.findById(orderItem.getSkuId());
                sku.setNum(sku.getNum()+orderItem.getNum());
                skuService.update(sku);
            }
        }



    }



    /**
     * 根据id查询所选所有未发货订单
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Order> findStatusById(Map<String, Object> searchMap) {

        for (String s : searchMap.keySet()) {
            System.out.println(s);
        }

        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("consignStatus", searchMap.get("consignStatus"));
        criteria.andIn("id",(List)searchMap.get("ids"));

        return orderMapper.selectByExample(example);
    }


    /**
     * 发货，修改订单日志
     *
     * @param orderList
     */
    @Override
    public void updateOrderLog(List<Order> orderList) {
        OrderLog orderLog = new OrderLog();

        for (Order order : orderList) {
            if (order.getShippingName() == null && order.getShippingCode() == null) {
                throw new RuntimeException("请填写完整的物流信息");
            }else {
                order.setOrderStatus("3");
                order.setConsignStatus("2");
                order.setConsignTime(new Date());
                orderMapper.updateByPrimaryKeySelective(order);


                orderLog.setId(idWorker.nextId()+"" );
                orderLog.setOperater("system");
                orderLog.setOperateTime(new Date());
                orderLog.setOrderId(order.getId());
                orderLog.setConsignStatus("1");
                orderLog.setOrderStatus("1");
                orderLog.setPayStatus("1");
                orderLog.setRemarks(order.getBuyerMessage());
                orderLogMapper.updateByPrimaryKeySelective(orderLog);
            }
        }
    }





    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }
    
            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }
    
        }
        return example;
    }

}
